<?php
//connect to mysql database
require("config.php");
//start session
session_start();

//if the user attempts to add something to the cart from the product page
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
	$wasFound = false;
	$i = 0;
	// If the cart session variable is not set or cart array is empty
	if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
	    // RUN IF THE CART IS EMPTY OR NOT SET
		$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
		$sql = mysql_query("UPDATE products SET quantity = quantity-1 WHERE id='$pid'");
	} else {
		// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
		foreach ($_SESSION["cart_array"] as $each_item) { 
		      $i++;
		      while (list($key, $value) = each($each_item)) {
				  if ($key == "item_id" && $value == $pid) {
					  // That item is in cart already; adjust its quantity using array_splice()
					  array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
					  $wasFound = true;
				  } // close if condition
		      } // close while loop
	       } // close foreach loop
			   if ($wasFound == false) {
			   array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
			   $sql = mysql_query("UPDATE products SET quantity = quantity-1 WHERE id='$pid'");
		   }
	}
	header("location: ../cart.php"); 
    exit();
}
?>
<?php
//if user chooses to empty their shopping cart
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
		unset($_SESSION["cart_array"]);
		$sql = mysql_query("UPDATE products SET quantity = original_quantity");
}
?>
<?php
//if user chooses to adjust item quantity
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
    // execute some code

	$item_to_adjust = $_POST['item_to_adjust'];
	
	$quantity = $_POST['quantity'];
	$quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
	if ($quantity >= 100) { $quantity = 99; }
	if ($quantity < 1) { $quantity = 1; }
	if ($quantity == "") { $quantity = 1; }
	$i = 0;
	foreach ($_SESSION["cart_array"] as $each_item) { 
		      $i++;
		      while (list($key, $value) = each($each_item)) {
				  if ($key == "item_id" && $value == $item_to_adjust) {
					  // That item is in cart already so adjust its quantity using array_splice()
					  array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
						$qty = mysql_query("SELECT original_quantity FROM products WHERE id='$item_to_adjust'");
						$orig_qty = mysql_fetch_assoc($qty);
						
					if($quantity > $orig_qty["original_quantity"]) { 
						$sql = mysql_query("UPDATE products SET quantity = original_quantity WHERE id='$item_to_adjust'"); ?>
							<script language="javascript">
							<!--error if quantity is more than original quantity -->
								window.alert("Error. Max Stock: " + <?php echo $orig_qty["original_quantity"]; ?>);
								document.location="../cart.php";	  
							</script>
				<?php } else {
						$sql = mysql_query("UPDATE products SET quantity = original_quantity-'$quantity' WHERE id='$item_to_adjust'");
					  }
				  } // close if condition
		      } // close while loop
	} // close foreach loop	
		header("location: ../cart.php"); 
}
?>
<?php
//if user wants to remove an item from cart
if(isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "" && isset($_POST['item_to_remove']) && $_POST['item_to_remove'] != "") {
	//access the array and run the code to remove that array index
	
	$key_to_remove = $_POST['index_to_remove'];
	$item_to_remove = $_POST['item_to_remove'];
	if(count($_SESSION["cart_array"]["$key_to_remove"]) <= 1) {
		unset($_SESSION["cart_array"]);
		$sql = mysql_query("UPDATE products SET quantity = original_quantity");
	} else {
		unset($_SESSION["cart_array"]["$key_to_remove"]);
		$sql = mysql_query("UPDATE products SET quantity = original_quantity WHERE id='$item_to_remove'");
		sort($_SESSION["cart_array"]);
	}
	header("location: ../cart.php"); 
}
?>
<?php
//render the cart for the user to view on  the page
$cartOutput ="";
$cartTotal = "";
$cartArticles = "";

$quantity = $_POST['quantity'];
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
	$cartOutput = "<h2 align='center'>Your Shopping Cart is empty</h2><br />";
	$cartTotal = "Total: $0.00";
	$cartArticles = 0;
} else {
	$i = 0;
	foreach($_SESSION["cart_array"] as $each_item){
		$item_id = $each_item['item_id'];//variable to access the database for that item
		$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
		//access each variable from database
		$cartArticles = $each_item['quantity'] + $cartArticles;
		while($row = mysql_fetch_array($sql)) {
			$product_name = $row["product_name"];
			$price = $row["price"];
			$details = $row["details"];
		}	
		$original_qty = mysql_query("SELECT original_quantity FROM products WHERE id='$item_id'");
		if ($quantity > $original_quantity) {
			$stockOut = "error";
		}
		$priceTotal = $price * $each_item['quantity'];
		$cartTotal = $priceTotal + $cartTotal;
		
		setlocale(LC_MONETARY, "en_US");
		$priceTotal = money_format("%10.2n", $priceTotal);
		$price2 = money_format("%10.2n", $cartTotal);
		//dynamic table row assembly
		$cartOutput .= "<tr align='center'>";
		$cartOutput .= '<td><a href="product.php?id='.$item_id.'">'.$product_name.'</a><br /><img style="margin:5px;" src="inventory_images/'.$item_id.'.jpg" alt="'.$product_name.'" width="50" height="62" border="1"/></td>';
		$cartOutput .= "<td>".$details."</td>";
		$cartOutput .= "<td>$".$price."</td>";
		$cartOutput .= '<td><form action="storescripts/cart_script.php" method="post">
		<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
		<br /><br />
		<input name="adjustBtn' . $item_id . '" type="submit" value="change" />
		<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
		</form></td>';
		//$cartOutput .= "<td>".$each_item['quantity']."</td>";
		$cartOutput .= "<td>".$priceTotal."</td>";
		$cartOutput .= '<td><form action="storescripts/cart_script.php" method="post">
			<input name="deleteBtn' . $item_id . '" type="submit" value="Remove" />
			<input name="index_to_remove" type="hidden" value="' . $i . '" />
			<input name="item_to_remove" type="hidden" value="'.$item_id.'"/></form></td>';
		$cartOutput .= "</tr>";
		$i++;
	}
	setlocale(LC_MONETARY, "en_US");
	$cartTotal = money_format("%10.2n", $cartTotal);
	$cartTotal = "Total : ".$cartTotal;
}
?>